<?php


namespace app\api\controller;


use app\BaseController;

//引入模型
use app\common\service\TenImService;
use app\models\user\Users;
use app\models\user\UserToken;
use app\models\system\Stocks;

//处理redis

use app\Request;
use broadcast\services\UtilService as Util;
use think\facade\Db;
use app\models\system\Robots;
use app\models\user\Envelopes;
use app\models\user\EnvelopesRecord;

use app\models\system\Prohibit;
use app\models\user\UserSign;
use broadcast\redis\setRedis;
use broadcast\redis\RedisRecord;
use Exception;

/**
 * Class Index
 * @package app\api\controller
 */
class User extends BaseController
{
    //获取当前用户的信息
    public function useinfo(Request $request)
    {
        session('website', $request->website());
        $uid = $request->uid();
        $info = setRedis::getUserCache(session("website"), 'usersList#' . $uid . ':*');
        $userInfo = array();
        if ($info) {
            $userInfo = $info['data'];
        } else {
            $userInfo = Users::where('id', $uid)->find()->toArray();
        }
        // halt($info);    
        $userInfo['balance'] = round($userInfo['balance'], 2);
        $userinfo['create_ip'] = getIp($userInfo['create_ip']);

        return app("json")->success($userInfo);
    }

    //登录
    public function login(Request $request)
    {
        $data = Util::postMore([
            ['username', ''],
            ['password', ''],
            ['roomid', ''],
        ]);
        session('website', $request->website());
        $Banlean = new Prohibit();
        $data['ip'] = getIps();
        //判断是否为被封禁用户或IP   start
        if ($data['username'] != '') {
            $Banlean = $Banlean->where("username", $data['username']);
            if ($data['ip'] == '') {
                $Banlean = $Banlean->whereOr("ip", ip2long(getIps(true)));
            }else {
                $Banlean = $Banlean->whereOr("ip", ip2long($data['ip']));
            }
        }

        $Banlean = $Banlean->find();
        if ($Banlean) return app("json")->fail("用户名或IP受限！");
        //判断是否为被封禁用户或IP   end

        $info = setRedis::getUserCache(session("website"), 'usersList#*:' . $data['username']);

        if (!$info) {
            $info = Users::where('username', $data['username'])->where("password", md5($data['password']))->find();
            if (empty($info)) return app("json")->fail("用户不存在");
            setRedis::setCache(session("website"), "usersList#" . $info['id'] . ":" . $info['username'], $info->toArray(), 0);
        } else {
            $info = $info['data'];
        }
        if ($info['group'] == 0) {
            $info = false;
        }

        if ($info['password'] != md5($data['password'])) return app("json")->fail("用户名或密码不正确");

        if ($info['status'] == 0) return app("json")->fail("用户被冻结");

        if ($info) {
            $time = strtotime("+ 500hour");
            $token = UserToken::tokenCreate($info['id'], $time);
            //用户登录记录    start
            //用户登录记录    end

            // 更新用户信息
            if ($data['ip'] != '') {
                Users::where("id", $info['id'])->update(['lately_time' => time(), 'create_ip' => setIp($data['ip']), 'create_home' => ascriptions($data['ip']), 'online' => 1]);
                $info['create_ip'] = setIp($data['ip']);
                $info['create_home'] = ascriptions($data['ip']);
            }

            $info['lately_time'] = time();
            $info['online'] = 1;

            setRedis::setCache(session('website'), 'usersList#' . $info['id'] . ":" . $info['username'], $info, 0);

            $info['sex'] = $info['sex'] == 1 ? '男' : '女';

            // 获取IM配置
            $imSettings = TenImService::getSettings($data['roomid'], $info);

            //处理多余数据
            unset($info['id']);
            unset($info['password']);
            unset($info['create_time']);
            unset($info['create_ip']);
            unset($info['lately_time']);
            unset($info['create_home']);
            unset($info['openid']);
            unset($info['realname']);
            unset($info['website']);
            unset($info['status']);
            unset($info['update_time']);
            unset($info['extension']);
            unset($info['online']);
            unset($info['nickname']);

            $info['balance'] = round($info['balance'], 2);

            return app("json")->success('登录成功', ['token' => $token, 'expires_time' => $time, 'userInfo' => $info, 'imSettings' => $imSettings]);
        }
        return app("json")->fail("用户名或密码不正确");
    }

    //游客登录
    public function tourist_login(Request $request)
    {
        $data = Util::postMore([
            ['roomid', '']
        ]);
        session('website', $request->website());
        $data['ip'] = getIps();

        $Banlean = new Prohibit();
        //判断是否为被封禁用户或IP   start
        if ($data['ip'] == '') {
            $Banlean = $Banlean->whereOr("ip", ip2long(getIps(true)));
        }else {
            $Banlean = $Banlean->whereOr("ip", ip2long($data['ip']));
            
        }

        $Banlean = $Banlean->find();
        if ($Banlean) return app("json")->fail("用户名或IP受限！");
        //判断是否为被封禁用户或IP   end

        $other = getGuid();
        $info = array();
        $info['id'] = 'yk' . $other;
        $info['username'] = 'yk' . $other;
        // $info['nickname'] = '游客' . $other;
        $info['sex'] = '男';
        $info['email'] = '';
        
        if ($data['ip']) {
            $info['create_ip'] = setIp($data['ip']);
            $info['create_home'] = ascriptions($data['ip']);
        }
        
        $info['website'] = session("website");
        $info['rooms'] = $data['roomid'];
        $info['group'] = 857;
        $info['phone'] = '';
        $info['portrait'] = '';


        $time = strtotime("+ 500hour");
        $token = lockcode($info['id'], 'ENCODE');

        setRedis::setCache(session("website"), "touristList#" . $info['username'], $info, 0);

        unset($info['create_ip']);

        // 获取IM配置
        $imSettings = TenImService::getSettings($data['roomid'], $info);
        unset($info['id']);
        unset($info['website']);
        unset($info['create_ip']);
        unset($info['create_home']);

        //用户登录记录    start
        //用户登录记录    end
        return app("json")->success('登录成功', ['token' => $token, 'expires_time' => $time, 'userInfo' => $info, 'imSettings' => $imSettings]);
    }

    public function getUserSig(Request $request)
    {
        $data = Util::getMore([
            ['roomid', '']
        ]);
        if (!$data['roomid']) return app("json")->fail("房间号不能为空");
        $uid = $request->uid();
        $website = session("website");
        if (substr($uid, 0, 2) == 'yk') {
            $userInfo = setRedis::getUserCache($website, 'touristList#' . $uid);
        } else {
            $userInfo = setRedis::getUserCache($website, 'usersList#' . $uid . ':*');
        }
        if (!$userInfo) return app("json")->fail("用户信息不存在[{$website}:touristList#{$uid}]");
        $userInfo = $userInfo['data'];
        $params = TenImService::getAccount($data['roomid'], $userInfo);
        $userSig = TenImService::getUserSig($params);
        return app("json")->success("ok", ['user_sig' => $userSig]);
    }

    /**
     * 机器人配置
     */
    public function robots(Request $request)
    {
        $data = Util::postMore([
            ['roomid', ''],
            ['robots', 0]
        ]);

        session('website', $request->website());
        $uid = $request->uid();

        if (strpos($uid, 'yk') !== false) return app("json")->success([]);
        $list = array();
        //机器人权限组
        $robotGroup = 858;

        //游客机器人
        // if ($data['robots'] != 0) {
        //     $touristRobot = array_fill(0, $data['robots'], ['rooms' => $data['roomid'], 'group' => $robotGroup, 'extension' => -1, 'sex' => '男', 'email' => '--', 'create_time' => time(), 'create_ip' => '--', 'lately_time' => time(), 'create_home' => '--', 'phone' => '--', 'realname' => '--', 'portrait' => '', 'status' => 1]);

        //     $robots_i = 100;
        //     foreach ($touristRobot as &$value) {
        //         $value['id'] =  '游客' . $robots_i;
        //         $value['username'] =  '游客' . $robots_i;
        //         $robots_i++;
        //     }
        //     $list = array_merge($list, $touristRobot);
        // }

        //获取会员机器人
        if ($data['roomid'] == 888) {
            //开会房间
            $list = [];
        } else {
            $nowRid = $data['roomid'];
            //处理互通规则 start
            // $interwork = setRedis::getCache(session("website"),'nowInterWork');

            // if (!empty($interwork)) $interworkList = array_column($interwork, 'roomds');
            // foreach ($interworkList as $value) {
            //     $item = explode(",",$value);
            //     if (in_array($data['roomid'],$item)) {
            //         $nowRid = $value;
            //     }
            // }

            //处理互通规则  end

            $info = setRedis::getUserCache(session("website"), "usersList#{$uid}:*");
            if (!$info) {
                $info = Users::where('id', $uid)->find();
                if (empty($info)) return app("json")->fail("用户不存在");
                setRedis::setCache(session("website"), "usersList#" . $info['id'] . ":" . $info['username'], $info->toArray(), 0);
            } else {
                $info = $info['data'];
            }

            $memberRobots = Robots::where("operator", $info['username'])->limit(100)->select()->toArray();
            //处理数据
            foreach ($memberRobots as &$value) {
                $value['id'] = 'robot_' . $value['id'];
                $value['extension'] = $value['operator'];
                $value['username'] = $value['name'];
                unset($value['name']);
                unset($value['operator']);
                $value['sex'] = '男';
                $value['email'] = '--';
                $value['create_time'] = time();
                $value['create_ip'] = '--';
                $value['lately_time'] = time();
                $value['create_home'] = '';
                $value['phone'] = '--';
                $value['realname'] = '--';
                $value['portrait'] = '';
                $value['status'] = 1;
                $value['rooms'] = $data['roomid'];
                $value['group'] = $value['gid'];
            }
            //处理数据


            $list = array_merge($list, $memberRobots);
        }
        shuffle($list);

        return app("json")->success($list);

    }

    /**
     * 用户签到
     */
    public function sign(Request $request)
    {
        //用户id

        $uid = $request->uid();
        if (strpos($uid, 'yk') !== false) return app("json")->success('游客状态无法签到');

        // 用户签到  4个小时内不能签到
        $nowTime = time();
        $key = 'userSign:' . $uid;
        $sign = setRedis::getCache($request->website(), $key);

        if ($sign) {
            if (((int)$sign['time'] + (4 * 60 * 60)) > $nowTime) {
                return app("json")->success('已经签到过了');
            } else {
                $sign = ['time' => $nowTime, 'num' => $sign['num'] + 1];
                setRedis::setCache($request->website(), $key, $sign);
                UserSign::create(['uid' => $uid,'add_time'=>$nowTime,'total' => $sign['num'],'today'=> Db::connect($request->website())->table("chat_user_sign")->whereDay("add_time")->count()+1]);
                return app("json")->fail("签到成功", ['num' => $sign['num'], 'time' => date("Y-m-d H:i:s", $nowTime)]);
            }
        } else {
            $sign = ['time' => $nowTime, 'num' => 1];
            setRedis::setCache($request->website(), $key, $sign);
            UserSign::create(['uid' => $uid,'add_time'=>$nowTime,'total' => $sign['num'],'today'=> Db::connect($request->website())->table("chat_user_sign")->whereDay("add_time")->count()+1]);
            return app("json")->fail('签到成功', ['num' => 1, 'time' => date('Y-m-d H:i:s', $nowTime)]);

        }


    }

    /**
     * 个股诊断
     */
    public function diagnosis(Request $request)
    {
        session('website', $request->website());
        $data = Util::postMore([
            ['code', ''],
            ['cost', ''],
            ['position', ''],
            ['diagnosis', '']
        ]);
        //用户id
        $uid = $request->uid();
        if (strpos($uid, 'yk') !== false) return app("json")->success('游客状态无法签到');

        if ($data['code'] == '') return app("json")->fail("代码不能为空");
        if ($data['cost'] == '') return app("json")->fail("成本不能为空");
        if ($data['position'] == '') return app("json")->fail("仓位不能为空");
        if ($data['diagnosis'] == '') return app("json")->fail("诊断方向不能为空");

        $data['add_people'] = $request->uid();
        $data['create_time'] = time();

        $stocks = new Stocks;
        $res = $stocks->save($data);
        return $res ? app("json")->success('添加成功') : app("json")->success('添加失败');
    }


    /**
     * 用户修改
     */
    public function userEdit(Request $request)
    {
        $data = Util::postMore([
            ['sex', '']
        ]);
        if ($data['sex'] == '') return app("json")->success("修改成功");
        session('website', $request->website());
        $uid = $request->uid();

        Users::where("id", $uid)->update(['sex' => $data['sex']]);

        $info = setRedis::getUserCache(session("website"), 'usersList#' . $uid . ':*');
        if ($info) {
            $key = $info['key'];
            $info['data']['sex'] = $data['sex'];

            $keyLsit = explode(":", $key);
            unset($keyLsit[0]);
            $nowKey = implode(":", $keyLsit);

            setRedis::setCache(session("website"), $nowKey, $info['data'], 0);
        }

        return app("json")->success("修改成功");
    }

    /**
     * 密码修改
     */
    public function userEditPass(Request $request)
    {
        $data = Util::postMore([
            ['primary', ''],
            ['password', '']
        ]);
        $nowKey = '';
        if ($data['primary'] == '') return app("json")->fail("原密码不能为空");
        if ($data['password'] == '') return app("json")->fail("新密码不能为空");
        session('website', $request->website());
        $uid = $request->uid();
        $info = setRedis::getUserCache(session("website"), 'usersList#' . $uid . ':*');
        if ($info) {
            $key = $info['key'];
            $keyLsit = explode(":", $key);
            unset($keyLsit[0]);
            $nowKey = implode(":", $keyLsit);
            $info = $info['data'];
        } else {
            $info = Users::where("id", $uid)->find()->toArray();
        }

        if ($info['password'] == md5($data['primary'])) {
            $info['password'] = md5($data['password']);
            if ($nowKey != '') setRedis::setCache(session("website"), $nowKey, $info, 0);
            Users::where("id", $uid)->update(['password' => md5($data['password'])]);
        } else {
            return app("json")->fail("原密码错误");
        }
    }

    /**
     * 用户下线
     */
    public function userOffline()
    {
        $data = Util::postMore([
            ['id', ''],
            ['website', '']
        ]);

        session('website', $data['website']);
        $res = Users::where('id', $data['id'])->update(['online' => 0]);
        return $res ? app("json")->success("下线成功") : app("json")->fail("下线成功");
    }
   
    //发红包
    public function sendEnvelopes(Request $request)
    {
        $data = Util::postMore([
            ['total', 0],
            ['number', 0],
            ['roomid', 0]
        ]);

        if ($data['total'] == 0) return app("json")->fail("参数错误");
        if ($data['number'] == 0) return app("json")->fail("参数错误");
        if ($data['roomid'] == 0) return app("json")->fail("参数错误");

        $uid = $request->uid();

        if (strpos($uid, 'yk') !== false) return app("json")->success('游客状态无法发送红包');

        session('website', $request->website());

        try {
            //处理当前用户余额
            $userInfo = setRedis::getUserCache(session("website"), "usersList#" . $uid . ":*");
            if ((float)$userInfo['data']['balance'] < $data['total']) {
                return app("json")->fail("用户金额不足");
            }
            $save = Users::where('id', $uid)->dec("balance", (float)$data['total'])->save();
            if ($userInfo) {
                $userInfo['data']['balance'] = round((float)$userInfo['data']['balance'] - (float)$data['total'], 2);
                setRedis::setCache(session("website"), "usersList#" . $uid . ":" . $userInfo['data']['username'], $userInfo['data'], 0);
            }
            if ($save) {
                $envelopes = new \broadcast\services\Envelopes((int)$data['number'], (float)$data['total']);
                $envelopeslist = $envelopes->compute();

                //红包处理
                $redEnvelopesHandle = new RedisRecord(session("website"), 'redEnvelopesHandle');
                $envelopesIdent = $redEnvelopesHandle->setEnvelopes($envelopeslist, $userInfo['data']);

                //添加记录    --   1  添加红包记录
                Envelopes::create(['id' => $envelopesIdent, 'uid' => $uid, 'price' => $data['total'], 'number' => $data['number'], 'create_time' => time(), 'surplus_price' => $data['total'], 'surplus_number' => $data['number'], 'roomid' => $data['roomid']]);

                return app("json")->success(['time' => $envelopesIdent]);

            } else {
                return app("json")->fail("发送红包失败");
            }

        } catch (Exception $e) {
            return app("json")->fail("发送红包失败");
        }


    }

    /**
     * 领取红包
     */
    public function getEnvelopes(Request $request)
    {
        $data = Util::postMore([
            ['ident', 0],
        ]);

        if ($data['ident'] == 0) return app("json")->fail("参数错误");

        $uid = $request->uid();

        if (strpos($uid, 'yk') !== false) return app("json")->success('游客状态无法领取红包');

        session('website', $request->website());

        try {
            $redEnvelopesHandle = new RedisRecord(session("website"), 'redEnvelopesHandle');
            $writeInfo = $redEnvelopesHandle->getEnvelopesInfo($data['ident'], $uid);
            if ($writeInfo) return app("json")->fail($writeInfo);
            $envelopes = $redEnvelopesHandle->getEnvelopes($data['ident'], $uid);
            if ($envelopes['price']) {

                $save = Users::where('id', $uid)->inc("balance", (float)$envelopes['price'])->save();
                $userInfo = setRedis::getUserCache(session("website"), "usersList#" . $uid . ":*");

                if ($userInfo) {
                    $userInfo['data']['balance'] = round((float)$userInfo['data']['balance'] + (float)$envelopes['price'], 2);
                    setRedis::setCache(session("website"), "usersList#" . $uid . ":" . $userInfo['data']['username'], $userInfo['data'], 0);
                }
                //修改红包数据
                Envelopes::where("id", $data['ident'])->dec('surplus_number', 1)->save();
                Envelopes::where("id", $data['ident'])->dec("surplus_price", $envelopes['price'])->save();
                //添加红包记录
                EnvelopesRecord::create(['eid' => $data['ident'], 'uid' => $uid, 'create_time' => time(), 'price' => $envelopes['price']]);

                return $save ? app("json")->success(['remind' => '领取红包成功', 'tip' => 200, 'envelopes' => $envelopes['price'], 'userinfo' => $envelopes['userinfo']]) : app("json")->success(['remind' => '红包已领取完', 'tip' => 205, 'envelopes' => 0]);

            } else {
                return app("json")->success(['remind' => '红包已领取完', 'tip' => 205, 'envelopes' => 0, 'userinfo' => $envelopes['userinfo']]);
            }

        } catch (Exception $e) {
            return app("json")->fail("领取失败");
        }
    }

}